package org.freespace.utils;

import org.apache.commons.net.telnet.TelnetClient;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.rmi.server.ExportException;
import java.util.Enumeration;

public class IpUtil {
    public static boolean ping(String ip) throws IOException {
        int timeOut = 2000;
        return InetAddress.getByName(ip).isReachable(timeOut);
    }

    public static boolean telnet(String ip, int port) throws IOException {
        TelnetClient telnetClient = new TelnetClient();
        try {
            telnetClient.connect(ip, port);
            return true;
        }catch (Exception e){
            return false;
        } finally {
            try {
                telnetClient.disconnect();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static String getIpAddress() {
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
                    continue;
                } else {
                    Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        ip = addresses.nextElement();
                        if (ip != null && ip instanceof Inet4Address) {
                            return ip.getHostAddress();
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("IP地址获取失败" + e.toString());
        }
        return "";
    }
}
